import Footer from '@/components/Footer';
import {
    userAuthLoginUsingPOST, userForgetPassword,
    userLoginUsingPOST,
    userRegisterUsingPOST,
    userSendUsingGET
} from '@/services/api-hub-be/userController';
import {
    AlipayCircleOutlined, createFromIconfontCN, GithubOutlined,
    LockOutlined, MobileOutlined,
    QqOutlined, SafetyOutlined,
    TaobaoCircleOutlined,
    UserOutlined,
    WeiboCircleOutlined,
} from '@ant-design/icons';
import {LoginFormPage, ProFormCheckbox, ProFormInstance, ProFormText,} from '@ant-design/pro-components';
import {useModel} from '@umijs/max';
import {Button, Form, message, Modal, Space, Tabs} from 'antd';
import type {CSSProperties} from 'react';
import React, {useEffect, useRef, useState} from 'react';
import logo from '../../../../public/logo.png';
import {ProFormCaptcha} from "@ant-design/pro-form";
import SliderCaptcha from "rc-slider-captcha";
import {sleep} from "ut2";

type LoginType = 'account' | 'register' | 'forgetPassword';

const iconStyles: CSSProperties = {
    fontSize: '24px',
    cursor: 'pointer',
};

const Login: React.FC = () => {
    const {initialState, setInitialState} = useModel('@@initialState');
    const [loginType, setLoginType] = useState<LoginType>('account');
    const formRef = useRef<ProFormInstance>();
    const [form] = Form.useForm();
    const [phoneOrEmail, setPhoneOrEmail] = useState<String>('');
    const [countdown, setCountdown] = useState(30);
    const [count, setCount] = useState(0);
    const [isCaptchaDisabled, setIsCaptchaDisabled] = useState(false);
    const [open, setOpen] = useState(false);
    const handlePhoneNumberChange = (event) => {
        setPhoneOrEmail(event.target.value);
    };
    const phoneRegex = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    const emailRegex = /^[a-zA-Z0-9_-]+@[qQ][qQ]\.com$/;

    const IconFont = createFromIconfontCN({
        scriptUrl: '//at.alicdn.com/t/c/font_4214635_d4hvie8sbt9.js',
    });

    // 第三方登录
    const handleAuthLogin = async (source: API.LoginSource) => {
        try {
            localStorage.removeItem("token")
            const res = await userAuthLoginUsingPOST(source);
            if (res.data) {
                window.location.href = res.data;
            } else {
                message.error(res.message);
            }
        } catch (e) {
            // console.log(e)
            message.error(e.response.data);
        }
    }

    // 提交表单
    const handleSubmit = async (values: API.UserRegisterRequest) => {
        // console.log(values)
        const {userPassword, checkPassword} = values;
        const isForget =  values['phoneOrEmail-forgatePassword'];
        // console.log(isForget)
        if (checkPassword) {
            // 第二次密码存在，则可能是忘记密码或者是注册
            if (userPassword !== checkPassword) {
                message.error('两次输入密码不一致！');
                return;
            }
            if (isForget){
                // isForget字段有值，说明当前是忘记密码
                values['phoneOrEmail'] = isForget;
                const { ["phoneOrEmail-forgatePassword"]: ignored, ...body } = values;
                const res = await userForgetPassword(body);
                if (res.code === 2000) {
                    // 注册成功
                    const defaultRegisterSuccessMessage = '注册成功！';
                    message.success(defaultRegisterSuccessMessage)
                    // 切换到登录
                    setLoginType('account');
                    // 重置表单
                    formRef.current?.resetFields();
                }
            }else{
                // 没有值，说明当前是注册
                const res = await userRegisterUsingPOST(values);
                if (res.code === 2000) {
                    // 注册成功
                    const defaultRegisterSuccessMessage = '注册成功！';
                    message.success(defaultRegisterSuccessMessage)
                    // 切换到登录
                    setLoginType('account');
                    // 重置表单
                    formRef.current?.resetFields();
                }
            }
        } else {
            // 登录
            try {
                localStorage.removeItem("token")
                const res = await userLoginUsingPOST({
                    ...values,
                });
                if (res.data) {
                    const defaultLoginSuccessMessage = '登录成功！';
                    message.success(defaultLoginSuccessMessage);
                    // 登录成功后处理
                    const urlParams = new URL(window.location.href).searchParams;
                    // 重定向到 redirect 参数所在的位置
                    location.href = urlParams.get('redirect') || '/';
                    // 保存登录状态
                    setInitialState({
                        loginUser: res.data,
                    });
                } else {
                    message.error(res.message);
                }
            } catch (e) {
                // console.log(e)
                message.error(e.response.data);
            }
        }
    };

    // 获取验证码
    const handleSmsSend = async () => {
        const phoneOrEmail = form.getFieldValue('phoneOrEmail')
        // console.log(phoneOrEmail)
        form.validateFields(['phoneOrEmail']).then(async () => {
            try {
                // 设置倒计时为60秒
                setIsCaptchaDisabled(true);
                setTimeout(() => {
                    setIsCaptchaDisabled(false);
                }, countdown * 1000);
                const res = await userSendUsingGET({phoneOrEmail});
                if (res.code == 2000) {
                    message.success('验证码发送成功！');
                } else {
                    message.warning(res.message)
                }
            } catch (e) {
                // console.log(e.response.data)
                // message.error(e.response.data);
                message.error("验证码发送失败")
            }
        }).catch((error) => {
            console.log('校验失败:', error.message);
        });
    }


    return (
        <div>
            <div
                style={{
                    backgroundColor: 'white',
                    height: 'calc(100vh)',
                    margin: 0,
                }}
            >

                <LoginFormPage
                    submitter={{
                        searchConfig: {
                            submitText: "确认",
                        },
                    }}
                    form={form}
                    // backgroundImageUrl= "/static/cover.png"
                    backgroundImageUrl="https://img1.imgtp.com/2023/08/20/0upj6PvY.png"
                    logo={logo}
                    title="API Hub"
                    subTitle="史上最好用的免费API接口平台"
                    initialValues={{
                        autoLogin: true,
                    }}
                    onFinish={async (values) => {
                        await handleSubmit(values as API.UserRegisterRequest);
                    }}
                    actions={
                        <Space
                            style={{
                                marginTop: 24,
                            }}
                            size={78}
                        >
                            <IconFont style={iconStyles} type="icon-github" onClick={() => handleAuthLogin('github')}/>
                            <IconFont style={iconStyles} type="icon-gitee" onClick={() => handleAuthLogin('gitee')}/>
                            <IconFont style={iconStyles} type="icon-QQ" onClick={() => handleAuthLogin('qq')}/>
                            <IconFont style={iconStyles} type="icon-weibo" onClick={() => handleAuthLogin('weibo')}/>
                        </Space>
                    }
                >
                    {
                        <Tabs
                            centered
                            activeKey={loginType}
                            onChange={(activeKey) => setLoginType(activeKey as LoginType)}
                        >
                            <Tabs.TabPane key={'account'} tab={'登录'}/>
                            <Tabs.TabPane key={'register'} tab={'注册'}/>
                        </Tabs>
                    }
                    {/*登录页面*/}
                    {loginType === 'account' && (
                        <>
                            <ProFormText
                                name="userAccount"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined/>,
                                }}
                                placeholder={'请输入用户名'}
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名是必填项！',
                                    },
                                    {
                                        min: 5,
                                        message: '用户名长度至少有5位'
                                    }
                                ]}
                            />
                            <ProFormText.Password
                                name="userPassword"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined/>,
                                }}
                                placeholder={'请输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项！',
                                    },
                                    {
                                        min: 8,
                                        message: '密码长度至少有8位'
                                    }
                                ]}
                            />

                            <div
                                style={{
                                    marginBottom: 24,
                                }}
                            >
                                <ProFormCheckbox noStyle name="autoLogin">
                                    自动登录
                                </ProFormCheckbox>
                                <a
                                    style={{
                                        float: 'right',
                                    }}
                                    onClick={() => setLoginType("forgetPassword")}
                                >
                                    忘记密码 ?
                                </a>
                            </div>
                        </>
                    )}
                    {/*注册页面*/}
                    {loginType === 'register' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined/>,
                                }}
                                name="userAccount"
                                placeholder={'请输入用户名'}
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名是必填项！',
                                    },
                                    {
                                        min: 4,
                                        message: '长度不能少于4位！',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined/>,
                                }}
                                name="userPassword"
                                placeholder={'请输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项！',
                                    },
                                    {
                                        min: 8,
                                        message: '长度不能少于8位！',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined/>,
                                }}
                                name="checkPassword"
                                placeholder={'请再次输入密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项！',
                                    },
                                    {
                                        min: 8,
                                        message: '长度不能少于8位！',
                                    },
                                ]}
                            />

                            <ProFormText
                                name="phoneOrEmail"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <MobileOutlined className={'prefixIcon'}/>,
                                }}
                                value={phoneOrEmail}
                                onChange={handlePhoneNumberChange}
                                placeholder={'手机号/邮箱'}
                                rules={[
                                    {
                                        validator: (_, value, callback) => {
                                            if (!value) {
                                                callback("请输入手机号或邮箱");
                                            }
                                            if (!phoneRegex.test(value) && !emailRegex.test(value)) {
                                                callback("手机号或邮箱格式错误");
                                            }
                                            callback();
                                        },
                                    },
                                ]}
                            />

                            <ProFormCaptcha
                                fieldProps={{
                                    size: 'large',
                                    prefix: <SafetyOutlined className={'prefixIcon'}/>,
                                }}
                                captchaProps={{
                                    size: 'large',
                                    disabled: isCaptchaDisabled,
                                }}
                                countDown={countdown}
                                placeholder={'请输入验证码'}
                                captchaTextRender={(timing, count) => {
                                    // if (timing) {
                                    //     return `${count} ${'获取验证码'}`;
                                    // }
                                    return isCaptchaDisabled ? `${count} ${'获取验证码'}` : '获取验证码';
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入验证码！',
                                    },
                                ]}
                                // onGetCaptcha={async () => {
                                //     // console.log("邮箱或手机号", phoneOrEmail)
                                //     await handleSmsSend(phoneOrEmail as API.UserSmsRequest);
                                // }}
                                onGetCaptcha={handleSmsSend}
                            />

                        </>
                    )}
                    {/*忘记密码页面*/}
                    {loginType === 'forgetPassword' && (
                        <>
                            <ProFormText
                                fieldProps={{
                                    size: 'large',
                                    prefix: <UserOutlined/>,
                                }}
                                name="userAccount"
                                placeholder={'请输入用户名'}
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名是必填项！',
                                    },
                                    {
                                        min: 4,
                                        message: '长度不能少于4位！',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined/>,
                                }}
                                name="userPassword"
                                placeholder={'请输入新密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项！',
                                    },
                                    {
                                        min: 8,
                                        message: '长度不能少于8位！',
                                    },
                                ]}
                            />
                            <ProFormText.Password
                                fieldProps={{
                                    size: 'large',
                                    prefix: <LockOutlined/>,
                                }}
                                name="checkPassword"
                                placeholder={'请再次输入新密码'}
                                rules={[
                                    {
                                        required: true,
                                        message: '密码是必填项！',
                                    },
                                    {
                                        min: 8,
                                        message: '长度不能少于8位！',
                                    },
                                ]}
                            />

                            <ProFormText
                                name="phoneOrEmail-forgatePassword"
                                fieldProps={{
                                    size: 'large',
                                    prefix: <MobileOutlined className={'prefixIcon'}/>,
                                }}
                                value={phoneOrEmail}
                                onChange={handlePhoneNumberChange}
                                placeholder={'手机号/邮箱'}
                                rules={[
                                    {
                                        validator: (_, value, callback) => {
                                            if (!value) {
                                                callback("请输入手机号或邮箱");
                                            }
                                            if (!phoneRegex.test(value) && !emailRegex.test(value)) {
                                                callback("手机号或邮箱格式错误");
                                            }
                                            callback();
                                        },
                                    },
                                ]}
                            />

                            <ProFormCaptcha
                                fieldProps={{
                                    size: 'large',
                                    prefix: <SafetyOutlined className={'prefixIcon'}/>,
                                }}
                                captchaProps={{
                                    size: 'large',
                                    disabled: isCaptchaDisabled,
                                }}
                                countDown={countdown}
                                placeholder={'请输入验证码'}
                                captchaTextRender={(timing, count) => {
                                    return isCaptchaDisabled ? `${count} ${'获取验证码'}` : '获取验证码';
                                }}
                                name="captcha"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入验证码！',
                                    },
                                ]}
                                onGetCaptcha={handleSmsSend}
                            />

                        </>
                    )}
                </LoginFormPage>
            </div>
            <Footer/>
        </div>
    );
};
export default Login;
